<template>
  <div>
    <div class="app-container">
      <el-form
        ref="formEl"
        :rules="rules"
        :model="from"
        class="app-form"
        label-width="120px"
      >
        <el-form-item label="产品名称" prop="modelName">
          <el-input
            v-model="from.modelName"
            max="24"
            placeholder="请填写产品名称"
          />
        </el-form-item>
        <el-form-item label="产品类别" prop="specialityCode">
          <Select
            v-model="from.specialityCode"
            :data="specialityList"
            style="width: calc(50% - 10px)"
            @change="pecialityChange()"
            placeholder="一级分类"
            @botton-click="bottonClick(1)"
          />

          <span style="display: inline-block; width: 20px; text-align: center"
            >--</span
          >
          <Select
            v-model="from.classificationCode"
            style="width: calc(50% - 10px)"
            :disabled="!from.specialityCode"
            @change="pecialityTwoChange()"
            :data="classificationList"
            placeholder="二级分类"
            @botton-click="bottonClick(2)"
          />
        </el-form-item>
        <!-- <el-form-item label="分类" prop="classificationCode">

      </el-form-item> -->
        <el-form-item label="部品规格" prop="threeCode">
          <Select
            style="width: 100%"
            v-model="from.threeCode"
            :disabled="!from.classificationCode"
            :isBtn="false"
            :data="threeList"
            placeholder="三级分类"
            @botton-click="bottonClick(3)"
          />
        </el-form-item>
        <el-form-item label="产品型号" prop="marking">
          <el-input v-model="from.marking" max="24" placeholder="请填写型号" />
        </el-form-item>
        <el-form-item label="产品编码" prop="modelCode">
          <el-input
            v-model="from.modelCode"
            max="24"
            placeholder="请填写编码"
          />
        </el-form-item>
        <el-form-item label="尺寸规格" prop="specifications">
          <el-input
            v-model="from.specifications"
            max="24"
            placeholder="请填写尺寸规格"
          />

          <!-- <el-tag v-for="tag in from.specifications" :key="tag" style="margin-right: 10px" closable size="large"
          :disable-transitions="false" @close="handleClose(tag)">
          {{ tag }}
        </el-tag>
        <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" style="width: 150px"
          @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
        <el-button v-else @click="showInput"> + 添加 </el-button> -->
        </el-form-item>

        <el-form-item label="区域" prop="province">
          <Province
            v-model="from.province"
            :data="provinceList"
            style="width: calc(50% - 10px)"
            @change="provinceChange()"
            :isBtn="false"
            placeholder="选择省"
            @botton-click="bottonClick(1)"
          />

          <span style="display: inline-block; width: 20px; text-align: center"
            >--</span
          >
          <Province
            v-model="from.city"
            style="width: calc(50% - 10px)"
            :disabled="!from.province"
            :data="cityList"
            :isBtn="false"
            placeholder="选择市"
            @botton-click="bottonClick(2)"
          />
        </el-form-item>
        <el-form-item label="标准体系" prop="system">
          <el-radio-group v-model="from.standard">
            <el-radio label="叠合剪力墙" />
            <el-radio label="钢结构" />
            <el-radio label="灌浆套筒" />
            <el-input v-model="from.standard" placeholder="自定义输入" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="预览图片" prop="thumbnailFileDtos">
          <!-- <UploadImg v-model:value="from.thumbnailFileDtos" /> -->

          <UploadImg
            :limit="6"
            :lableName="'authorizationLetter'"
            @upload="receiveFile"
            :imgUrl="''"
          />
          <!-- <el-upload
            class="avatar-uploader"
            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
            :show-file-list="false"
            :auto-upload="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-change="handleAvatarSuccess"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload> -->
          <!-- 自定义 -->
        </el-form-item>

        <!-- <el-form-item label="区域">
        <el-input
          v-model="from.economize"

          placeholder="省"
        />
        <el-input v-model="from.city"  placeholder="市" />
      </el-form-item> -->
        <el-form-item label="案例模型" prop="modelFileDtos">
          <div style="width: 100%; margin-bottom: 20px">
            <BigSmallType
              v-model="from.bigType"
              :data="bigTypeList"
              style="width: calc(50% - 10px)"
              :isBtn="false"
              @change="bigTypeChange"
              placeholder="大类"
              @botton-click="bottonClick(1)"
            />

            <span style="display: inline-block; width: 20px; text-align: center"
              >--</span
            >
            <BigSmallType
              v-model="from.smallType"
              style="width: calc(50% - 10px)"
              :disabled="!from.bigType"
              :isBtn="false"
              :data="smallTypeList"
              placeholder="小类"
              @botton-click="bottonClick(2)"
            />
          </div>
          <UploadFile
            :limit="6"
            :lableName="'authorizationLetter'"
            @upload="uploadFileChange"
            :accept="'.rfa'"
          ></UploadFile>

          <!-- <UploadFile
            v-model:value="from.modelFileDtos"
            accept=".rfa"
            keys="1"
          /> -->
        </el-form-item>

        <el-form-item label="附件" prop="databaseModelFileDtos">
          <!-- <UploadFile v-model:value="from.databaseModelFileDtos" keys="2" /> -->
          <UploadFile
            :limit="6"
            :lableName="'annex'"
            @upload="annexFileChange"
            :accept="''"
          ></UploadFile>
        </el-form-item>

        <!--      <el-form-item label="产品属性">
        <CascadeInput v-model:value="cascadeInput" />

        <el-button type="primary" @click="add">新增一级字段</el-button>
      </el-form-item>

      <el-form-item label="上传文档" prop="databaseModelFileDtos">
        <UploadFile v-model:value="from.databaseModelFileDtos" keys="2" />
      </el-form-item>

      <el-form-item label="上传图纸" prop="databaseModelFileDtos">
        <UploadFile v-model:value="from.databaseModelFileDtos" keys="2" />
      </el-form-item>


      <el-form-item label="案例名称" prop="modelName">
        <el-input v-model="from.modelName" max="24" placeholder="请填写案例名称" />
      </el-form-item>
      <el-form-item label="案例图片" prop="thumbnailFileDtos">
        <UploadImg v-model:value="from.thumbnailFileDtos" />
      </el-form-item>
      <el-form-item label="案例模型" prop="thumbnailFileDtos">
        <Select v-model="from.specialityCode" :data="specialityList" style="width: calc(50% - 10px);"
          @change="pecialityChange" placeholder="一级分类" @botton-click="bottonClick(1)" />

        <span style=" display: inline-block; width: 20px; text-align: center;">&#45;&#45;</span>
        <Select v-model="from.classificationCode" style="width: calc(50% - 10px);" :disabled="!from.specialityCode"
          :data="classificationList" placeholder="二级分类" @botton-click="bottonClick(2)" />
      </el-form-item>-->
      </el-form>
    </div>
    <div class="bottom-btn">
      <el-button @click="returnPage">取消</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
    <el-dialog
      :title="`新增${type == 1 ? '专业' : '分类'}`"
      v-model="dialogVisible"
      width="30%"
    >
      <el-form
        :model="dialogForm"
        ref="dialogFormRef"
        label-width="120px"
        :rules="dialogFormRules"
      >
        <el-form-item :label="type == 1 ? '专业' : '分类'" prop="dictName">
          <el-input v-model="dialogForm.dictName" style="width: 300px" />
        </el-form-item>
        <el-form-item label="编码" prop="dictValue">
          <el-input v-model="dialogForm.dictValue" style="width: 300px" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="submitData(type)"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import UploadImg from "@/components/Upload/UploadImgNew";
import UploadFile from "@/components/Upload/UploadFileNew";

import CascadeInput from "@/components/cascadeInput";
import Select from "@/components/Select";
import Province from "@/components/Province";
import BigSmallType from "@/components/BigSmallType";
import { Plus } from "@element-plus/icons-vue";

import { ref, reactive, nextTick, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import {
  insertModel,
  getModelInfo,
  updateModel,
  queryModelDictPage,
  insertModelType,
  queryProvince,
  queryBigSmallType,
} from "@/api/buildlibrary";
import { filePreview } from "@/api/file";

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;
const returnPage = () => {
  router.push("/modelmanagement");
};

onMounted(async () => {
  if (id) {
    getProvince();
    getBigSmallType();
    let res = await getModelInfo({ id });
    let datas = res.data;
    // console.log(res);
    // console.log(data);
    from.modelName = datas.modelName;
    from.modelCode = datas.modelCode;
    from.specialityName = datas.specialityName;
    from.marking = datas.marking;
    from.specialityCode = Number(datas.specialityCode);
    from.classificationCode = Number(datas.classificationCode);
    from.threeCode = Number(datas.threeCode);
    from.specifications = datas.specifications;
    from.province = datas.province;
    from.city = datas.city;
    from.standard = datas.standard;
    from.bigType = datas.bigType;
    smallTypeList.value = await queryBigSmallType(from.bigType);
    from.smallType = datas.smallType;

    from.classificationName = datas.classificationName;
    for (let index = 0; index < datas.thumbnailFileDtos.length; index++) {
      const res = await filePreview(
        datas.thumbnailFileDtos[index].minioFilePath
      );
      from.thumbnailFileDtos[index] = {
        ...datas.thumbnailFileDtos[index],
        url: res.data,
        name: datas.thumbnailFileDtos[index].minioFileName,
        fileUrl: datas.thumbnailFileDtos[index].minioFilePath,
      };
    }
    from.databaseModelFileDtos = datas.databaseModelFileDtos.map((t) => ({
      ...t,
      name: t.minioFileName,
      fileUrl: t.minioFilePath,
    }));
    from.modelFileDtos = datas.modelFileDtos.map((t) => ({
      ...t,
      name: t.minioFileName,
      fileUrl: t.minioFilePath,
    }));
    from.id = id;
    getList();
  } else {
    getProvince();
    getBigSmallType();
    getList();
  }
});

const specialityList = ref([]);
const classificationList = ref([]);
const threeList = ref([]);
const provinceList = ref([]);
const cityList = ref([]);
const bigTypeList = ref([]);
const smallTypeList = ref([]);

const getProvince = async () => {
  provinceList.value = await queryProvince();
};

const getBigSmallType = async () => {
  bigTypeList.value = await queryBigSmallType("type");
};

const getList = async () => {
  try {
    const res = await queryModelDictPage({
      model: {
        dictType: "",
      },
      current: 1,
      size: 9999,
    });
    let data = res.data.records;
    let status = res.code;
    console.log(data);
    if (status === 200) {
      specialityList.value = data;

      if (id || from.specialityCode) {
        specialityList.value.forEach((t) => {
          if (t.id == from.specialityCode) {
            classificationList.value = t.children;
          }
        });
      }

      if (id || from.classificationCode) {
        classificationList.value.forEach((t) => {
          if (t.id == from.classificationCode) {
            threeList.value = t.children;
          }
        });
      }

      if (id || from.province) {
        provinceList.value.forEach((t) => {
          if (t.name == from.province) {
            cityList.value = t.children;
          }
        });
      }
    }
  } catch (error) {}
};

/* 表单 */
const cascadeInput = ref([]);
const add = () => {
  cascadeInput.value.push({
    field: "",
    keys: "",
    expand: true,
  });
};
const formEl = ref(null);
const rules = reactive({
  modelName: [{ required: true, message: "请输入名称", trigger: "change" }],
  modelCode: [{ required: true, message: "请输入编码", trigger: "change" }],
  marking: [{ required: true, message: "请输入型号", trigger: "change" }],
  specialityCode: [
    { required: true, message: "请选择专业", trigger: "change" },
  ],
  classificationCode: [
    { required: true, message: "请选择分类", trigger: "change" },
  ],
  thumbnailFileDtos: [
    {
      required: true,
      message: "请上传缩略图",
      trigger: ["change", "blur"],
      type: "array",
    },
  ],
  specifications: [
    { required: true, message: "请添加尺寸规格", trigger: ["change", "blur"] },
  ],
  modelFileDtos: [
    {
      required: true,
      message: "请上传模型文件",
      trigger: ["change", "blur"],
      type: "array",
    },
  ],
  databaseModelFileDtos: [
    {
      required: true,
      message: "请上传附件",
      trigger: ["change", "blur"],
      type: "array",
    },
  ],
});
const from = reactive({
  modelName: "",
  marking: "",
  specialityName: "",
  specialityCode: "",
  classificationCode: "",
  classificationName: "",
  system: "",
  // economize: "",
  // city: "",
  thumbnailFileDtos: [],
  specifications: [],
  modelFileDtos: [],
  databaseModelFileDtos: [],
});

const submit = () => {
  formEl.value.validate(async (valid, fields) => {
    if (valid) {
      const fun = id ? updateModel : insertModel;
      try {
        const data = {
          ...from,
          thumbnailFileDtos: from.thumbnailFileDtos.map((t, i) => {
            if (t.status && t.status === "ready") {
              ElMessage.error(`第${i + 1}张未上传，请删除重新再上传！`);
              throw new Error(`第${i + 1}张未上传，请删除重新再上传！`);
            }
            return {
              minioFilePath: t.fileUrl,
              minioFileName: t.name,
              orderNo: i,
            };
          }),
          modelFileDtos: from.modelFileDtos.map((t, i) => {
            if (t.status && t.status === "ready") {
              ElMessage.error(`${t.name}未上传，请删除后重新上传！`);
              throw new Error(`${t.name}未上传，请删除后重新上传！`);
            }
            return {
              minioFilePath: t.fileUrl,
              minioFileName: t.name,
              orderNo: i,
            };
          }),
          databaseModelFileDtos: from.databaseModelFileDtos.map((t, i) => {
            if (t.status && t.status === "ready") {
              ElMessage.error(`${t.name}未上传，请删除后重新上传！`);
              throw new Error(`${t.name}未上传，请删除后重新上传！`);
            }
            return {
              minioFilePath: t.fileUrl,
              minioFileName: t.name,
              orderNo: i,
            };
          }),
        };
        let obj = specialityList.value.find(
          (t) => t.id === data.specialityCode
        );
        data.specialityName = obj.dictName;
        // data.classificationName = obj.children.find(
        //   (t) => t.id === data.classificationCode
        // ).dictName;

        let classification = obj.children.find(
          (t) => t.id === data.classificationCode
        );
        data.classificationName = classification.dictName;

        let three = classification.children.find(
          (t) => t.id === data.threeCode
        );
        data.threeName = three.dictName;

        const { status } = await fun(data);
        if (status === 200) {
          ElMessage({
            message: `${id ? "编辑" : "新增"}成功`,
            type: "success",
          });
          returnPage();
        } else {
          ElMessage({
            message: "服务器故障，稍后再试！",
            type: "warning",
          });
        }
      } catch (error) {
        console.log(error);
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

/* 标签相关逻辑 */
const inputValue = ref("");
const inputVisible = ref(false);
const InputRef = ref(null);
const handleClose = (tag) => {
  from.specifications.splice(from.specifications.indexOf(tag), 1);
};
const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value.input.focus();
  });
};
const handleInputConfirm = () => {
  if (inputValue.value) {
    from.specifications.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};

const pecialityChange = (value) => {
  from.classificationCode = "";
};
const pecialityTwoChange = () => {
  from.threeCode = "";
};

const provinceChange = () => {
  from.city = "";
};

const bigTypeChange = () => {
  from.smallType = "";
};

const imageUrl = ref("");
// 图片上传成功后的回调
const handleAvatarSuccess = (response, uploadFile) => {
  console.log(response, uploadFile);
  imageUrl.value = URL.createObjectURL(uploadFile.raw);
};

// 图片改变的回调

//图片before
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};

watch(
  () => from.bigType,
  (value) => {
    bigTypeList.value.forEach((t) => {
      if (t.value == value) {
        console.log(value, "value--------");
        smallTypeList.value = t.children;
      }
    });
  }
);

watch(
  () => from.province,
  (value) => {
    provinceList.value.forEach((t) => {
      if (t.name == value) {
        console.log(value, "value--------");
        cityList.value = t.children;
      }
    });
  }
);

watch(
  () => from.specialityCode,
  (value) => {
    specialityList.value.forEach((t) => {
      if (t.id == value) {
        console.log(value, "value--------");
        classificationList.value = t.children;
      }
    });
  }
);

/*watch(
  () => from.province,
  (value) => {
    debugger
    provinceList.value.forEach((t) => {
      debugger
      if (t.name == value) {
        cityList.value = t.children;
      }
    });
  }
);*/

watch(
  () => from.classificationCode,
  (value) => {
    classificationList.value.forEach((t) => {
      if (t.id == value) {
        console.log(value, "value--------");
        threeList.value = t.children;
      }
    });
  }
);

// 自定义专业模块
const dialogVisible = ref(false);
const dialogVisible2 = ref(false);
const type = ref("");
const dialogFormRef = ref(null);
const dialogFormRules = reactive({
  dictName: [
    {
      required: true,
      message: `请输入${type.value == 1 ? "专业" : "分类"}`,
      trigger: "blur",
    },
  ],
  dictValue: [{ required: true, message: "请输入编码", trigger: "blur" }],
});
let dialogForm = reactive({
  dictName: "",
  dictValue: "",
  parentId: 0,
  dictStatus: 0,
  dictSequence: 0,
});
// 下拉菜单点击
const bottonClick = (addType) => {
  type.value = addType;
  dialogVisible.value = true;
};

const submitData = (type) => {
  dialogFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      let data = {
        ...dialogForm,
        dictType: dialogForm.dictValue,
      };
      if (type == 2) {
        let obj = specialityList.value.find(
          (t) => t.id === from.specialityCode
        );
        data.parentId = obj.id;
        data.dictType = obj.dictType;
      }
      const { code } = await insertModelType(data);
      console.log(code);
      if (code === 200) {
        ElMessage.success(`添加成功`);
        dialogVisible.value = false;
        getList();
        closeDialog();
      } else {
        ElMessage.error("服务故障，稍后再试");
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const closeDialog = () => {
  dialogFormRef.value.resetFields();
  dialogVisible.value = false;
};

//图片上传逻辑
const receiveFile = (data) => {
  console.log(data);
};
//文件上传逻辑
const uploadFileChange = (data) => {
  console.log(data);
};
//附件上传逻辑
const annexFileChange = (data) => {
  console.log(data);
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  justify-content: center;
  height: calc(100vh - 164px);
  overflow: auto;
}

::v-deep .app-form {
  width: 80%;
  margin: 20px;

  .el-form-item__label {
    font-weight: 700;
  }
}

.bottom-btn {
  width: 100%;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top: 1px solid #eee;

  .el-button {
    width: 100px;
  }
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
